/**
 * HolySet
 */
package com.hs.gas.client;

import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;

import com.hs.gas.client.exceptions.PortBusyException;

/**
 * @author <a href="mailto:guangzong@gmail.com">Guangzong Syu</a>
 *
 */
public class TimerUtil {

	public static SerialPort initSerialPort(Config config) throws NoSuchPortException, PortBusyException {
		CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(config.get(Config.KEY_TIMER_PORT));
		if (portIdentifier.isCurrentlyOwned()) {
			throw new PortBusyException();
		}
		SerialPort serialPort = null;
		try {
			serialPort = (SerialPort) portIdentifier.open("timer", 200);
		} catch (PortInUseException e) {
			e.printStackTrace();
		}
		try {
			serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
					SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
			serialPort.notifyOnDataAvailable(true);
			serialPort.setOutputBufferSize(8);
		} catch (UnsupportedCommOperationException e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
		return serialPort;
	}
}
